package com.example.myapplication.base;

import android.os.Bundle;
import android.widget.Toast;

import com.example.myapplication.baseview.BaseMvpView;
import com.example.myapplication.mainactivity.presenter.Presenter;
import com.example.myapplication.utils.AppManager;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;

public abstract class BaseMvpActivity<P extends Presenter<V>, V extends BaseMvpView> extends AppCompatActivity
        implements BaseMvpView, LoaderManager.LoaderCallbacks<P> {

    private final int BASE_LODER_ID = 1000;//loader的id值
    protected P presenter;

    protected abstract int getResourcesId();

    protected abstract void initView();

    private boolean isFirst = true;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getResourcesId());
        getSupportLoaderManager().initLoader(BASE_LODER_ID, null, this);//初始化loader
        AppManager.addActivity(this);
        AppManager.setCurrentActivity(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (presenter != null) {
            presenter.attachView((V) this);//presenter与view 连接
        }
        if (isFirst) {
            initView();
            isFirst = false;
        }
    }

    @Override
    public void showErr(String err) {
        Toast.makeText(this,err,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onLoadFinished(Loader<P> loader, P data) {
        presenter = data;
        presenter.attachView((V) this);
    }

    @Override
    public void onLoaderReset(Loader<P> loader) {
        presenter = null;
    }

    @Override
    protected void onDestroy() {
        presenter.detachView();//presenter与view 断开连接
        super.onDestroy();
        AppManager.reomveActivity(this);
    }
}

